package walletsyslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncGameOrderFlowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSyncGameOrderFlowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncGameOrderFlowLogic {
	return &SyncGameOrderFlowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 同步游戏端钱包流水
func (l *SyncGameOrderFlowLogic) SyncGameOrderFlow(in *pb.SyncGameOrderFlowReq) (*pb.SyncGameOrderFlowResp, error) {
	defer utils.RecoverPanic()

	var err error
	for idx := 0; idx < len(in.List); idx++ {
		// 创建order流水
		var orderFlow wallet.UserGameOrderFlow
		var dOrderMoneyAmount decimal.Decimal
		dOrderMoneyAmount, err = decimal.NewFromString(in.List[idx].MoneyAmount)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		var dReturnMoneyAmount decimal.Decimal
		dReturnMoneyAmount, err = decimal.NewFromString(in.List[idx].ReturnAmount)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}

		iOrderMoneyAmount := dOrderMoneyAmount.Mul(decimal.NewFromInt(100)).RoundFloor(0).IntPart()
		iReturnMoneyAmount := dReturnMoneyAmount.Mul(decimal.NewFromInt(100)).RoundFloor(0).IntPart()

		orderFlow = wallet.UserGameOrderFlow{
			FlowNo:         uniqueid.GenFlowNoX(),
			ExternalFlowNo: in.List[idx].ExternalFlowNo,
			MoneyType:      in.List[idx].MoneyType,
			Uid:            in.List[idx].Uid,
			MoneyAmount:    iOrderMoneyAmount,
			GameId:         in.List[idx].GameId,
			ProviderId:     in.List[idx].ProviderId,
			State:          in.List[idx].State,
			ReturnAmount:   iReturnMoneyAmount,
			Multiplier:     in.List[idx].Multiplier,
		}

		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		orderFlow.OrderTime, err = time.ParseInLocation(dbkey.DateTimeCNFormat, in.List[idx].OrderTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}

		_, err = l.svcCtx.UserGameOrderFlowModel.InsertGameOrderFlow(l.ctx, &orderFlow)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}
	return &pb.SyncGameOrderFlowResp{}, nil
}
